﻿namespace Example
{
    using System.Diagnostics.CodeAnalysis;
    using System.Reflection;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    using Example.Models;
    using SimpleWebServices;
    using SimpleWebServices.Configuration;
    using SimpleWebServices.Data;
    using SimpleWebServices.Models;
    using SimpleWebServices.Web;
    using SimpleWebServices.Web.Mvc;
    using SimpleWebServices.Web.Routing;

    public class MvcApplication : HttpApplication
    {
        public static void InsertDistanceData()
        {
            AbsoluteUri urn = "urn://simplewebservices.org/distance/london/paris";

            (new Distance
            {
                Urn = urn,
                Token = RepositoryConfiguration.Resolve<Distance>().Token(urn),
                Cacheability = HttpCacheability.Public,
                Display =
                {
                    { "en", "212½ miles" },
                    { "fr", "342 km" }
                }
            }).Store<Distance>();
        }

        [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "ASP.NET requires the method to be an instance member.")]
        public void Application_Start()
        {
            ControllerBuilder.Current.SetControllerFactory(new StatelessControllerFactory());
            RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            if (MaintenanceConfiguration.Settings().Enabled)
            {
                RouteTable.Routes.Register<MaintenanceController>();
            }
            else
            {
                ModelBinders.Binders[typeof(ContactForm)] = new ModelBinder<ContactForm>();
                ModelBinders.Binders[typeof(LogOnForm)] = new ModelBinder<LogOnForm>();

                RouteTable.Routes.Register(Assembly.GetExecutingAssembly().GetTypes());
                RouteTable.Routes.Register<RootController>();
                RouteTable.Routes.Register<SiteController>();
                RouteTable.Routes.Register<FileController>();
                RouteTable.Routes.Register<TenantContentController>();
                RouteTable.Routes.Register<TenantStyleSheetController>();
                RouteTable.Routes.Register<ContentController>();
                RouteTable.Routes.Register<ExceptionController>();

                RouteTable.Routes.Register<NotFoundController>(); /// this must always be the last registration

                DataConfiguration.Settings().Upsert();
                MvcApplication.InsertDistanceData();
            }
        }
    }
}